<!--
 * @Author: your name
 * @Date: 2020-02-21 17:19:06
 * @LastEditTime: 2020-02-24 20:05:52
 * @LastEditors: Please set LastEditors
 * @Description: 表单页
 * @FilePath: /dongyang/src/views/Home.vue
 -->

<template>
  <div class="page-home" id="container">
    <div class="banner" >
      <img src="@/assets/banner.jpg" alt="" />
    </div>
    <div class="title">东阳市疫情防控检查表</div>
    <div class="form">
      <van-cell-group class="van-form">
        <van-cell title="1.所属乡镇街道*">
          <van-field
            readonly
            clickable
            :value="townLabel"
            placeholder="请选择所属乡镇街道"
          />
            <!-- @click="showPicker = true" -->
        </van-cell>
        <van-cell title="2.所属网格*">
          <span class="desc">填写“XX村/社区-XX网格”</span>
          <div class="market-name">
          <van-field v-model="form.grid_name" placeholder="请输入所属网格" @input="inputGridName" />
            <div class="box" v-if="gridName.length != 0">
              <p v-for="(item, index) in gridName" :key="index" @click="clickGridName(item.words)">{{item.words}}</p>
            </div>
          </div>
        </van-cell>
        <van-cell title="3.检查人姓名*">
          <van-field readonly v-model="form.check_name" placeholder="请输入检查人姓名" />
        </van-cell>
        <van-cell title="4.检查时间*">
          <van-field
            readonly
            v-model="form.check_at"
            placeholder="选选择检查时间"
            @click="showDate = true"
          />
        </van-cell>
        <van-cell title="5.场所名称*">
          <div class="market-name">
           <van-field v-model="form.market_name" placeholder="请输入场所详细名称" @input="inputName" />
           <div class="box" v-if="wordsName.length != 0">
             <p v-for="(item, index) in wordsName" :key="index" @click="clickName(item.words)">{{item.words}}</p>
           </div>
          </div>
        </van-cell>
        <van-cell title="6.场所地址*">
          <div class="market-name">
          <van-field v-model="form.market_address" placeholder="请输入场所详细地址" @input="inputAddress" />
           <div class="box" v-if="wordsAddress.length != 0">
             <p v-for="(item, index) in wordsAddress" :key="index" @click="clickAddress(item.words)">{{item.words}}</p>
           </div>
          </div>
          <div style="margin-top:10px;">GPS定位：{{form.market_gps}}</div>
        </van-cell>
        <van-cell title="7.场所类别*">
          <van-radio-group v-model="form.market_cate" direction="vertical">
            <van-radio
              :name="item.value"
              v-for="item in marketCate"
              :key="item.value"
              >{{ item.label }}</van-radio
            >
          </van-radio-group>
        </van-cell>
        <van-cell title="8.存在问题*">
          <van-checkbox-group v-model="form.market_problem" @change="changeBox">
            <van-checkbox
              shape="square"
              :disabled="getDisabled(item.value)"
              :name="Number(item.value)"
              v-for="item in marketProblem"
              :key="item.value"
              >{{ item.label }}
              </van-checkbox
            >
          </van-checkbox-group>
          <van-field v-if="showOther" v-model="form.market_problem_other" placeholder="请输入您的其他选项" />
        </van-cell>
        <van-cell title="9.现场整改情况*">
          <van-radio-group v-model="form.market_status">
            <van-radio name="1">已整改</van-radio>
            <van-radio name="2">未整改</van-radio>
          </van-radio-group>
        </van-cell>
        <van-cell title="10.请上传现场图片">
          <div class='upload-img'>
           <img :src="formatFull(image)" v-for="(image,index) in form.images" :key="index" alt="">
        <van-uploader  :after-read="addImage" /> 
          </div>
        </van-cell>
        <van-button size="large" type="primary" round @click="submit"
          >提交</van-button
        >
        <div @click="logout" class="logout">退出登录</div>
      </van-cell-group>
      <van-popup v-model="showPicker" position="bottom">
        <van-picker
          show-toolbar
          value-key="label"
          :columns="town"
          :default-index="defaultKey"
          @cancel="showPicker = false"
          @confirm="townConfirm"
        />
      </van-popup>
      <van-popup v-model="showDate" position="bottom">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @cancel="showDate = false"
          @confirm="selectDate"
        />
      </van-popup>
    </div>
  </div>
</template>
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { formConst, formGridc,formAdd,keySearch,keyGroup,keyAdd } from "@/apis";
import { uploadToUpyun,formatUpyunUrl,toLogin,loadAMap } from '@/utils'
@Component
export default class Home extends Vue {
  get formatFull() {
    return function(image: string) {
      return formatUpyunUrl(image,'full')
    }
  }
  private showPicker = false;
  private showDate = false;
  minDate = new Date(2020, 0, 1);
  maxDate = new Date(2020, 10, 1);
  currentDate = new Date();
  private townLabel: string = '' //街道名称
  private showOther: boolean = false //其他问题
  private wordsName: object[] = [] //场所名字
  private gridName: object[] = [] //网格
  private wordsAddress: object[] = [] //场所·地址 
  gnArr: any = []
  mnArr: any = []
  maArr: any = []
  gn:any = []
  mn:any = []
  ma: any = []
  arr2: any = []
  arr3: any = []
get getDisabled() {
  return function(value: number) {
    let arr = [2,3,4,6,11,13,16,17]
    if(arr.includes(+value)) {
      return true
    }
  }
}
  private form: any = {
    town_id: "", //街道id,
    grid_name: "", //所属网格
    check_name: "", //检查人名字
    check_at: "", //检查时间
    market_name: "", //场所名称
    market_address: "", //场所地址
    market_gps: "", //gps地址
    market_cate: "", //场所类别
    market_problem: [], //场所问题id
    market_problem_other: "", //其他问题时内容
    market_status: "", //现场整改(1已整改2未整改)
    images: []
  };
  private index: number = 0;
  private marketCate: any = [];
  private marketProblem: any = [];
  private town: any = [];
  private map: any = null;
  private defaultKey: number = 0
  mounted() {
   
    document.title = '东阳市疫情防控检查表'
    this.form.check_at = this.formatDateToString(new Date())
    this.formConst();
    this.init()
  }
  //关键字获取
  async keyGroup() {
   let data = await keyGroup()
   if(data && data.mn) {
      localStorage.setItem("mn", JSON.stringify(data.mn || []))
   }else {

    //  localStorage.setItem("mn", JSON.stringify([]))
   }
   if(data && data.ma) {
     localStorage.setItem("ma", JSON.stringify(data.ma || []))
   }else {
    //  localStorage.setItem("ma", JSON.stringify([]))
   }
   if(data && data.gn) {
      localStorage.setItem("gn", JSON.stringify(data.gn || []))
   }else {
      // localStorage.setItem("gn", JSON.stringify([]))
    //   let gn = JSON.parse(localStorage.getItem('gn') as string).concat([{type:"gn",words: this.form.grid_name}])
    //   let isHave = false
    //   console.log(gn,'gn');
      
    //  if(gn.length) {
    //     isHave = gn.some((item:any) => {
        
    //     return item.words === this.form.grid_name
    //   })
    //   }else {
    //     isHave = false
    //   }
    //   console.log(isHave,gn,'have');
      

    //   if(!isHave) {
    //     localStorage.setItem("gn", JSON.stringify(gn))
    //   }

   }
  }
  //添加图片
  public async addImage(file: any, detail: any) {
    const { url } = await uploadToUpyun(file.file);
    this.form.images.push(url)
  }
  //初始化地图
  public async init() {
      await loadAMap()
       let self = this
        AMap.plugin('AMap.Geolocation', function() {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
          })

          geolocation.getCurrentPosition()
          AMap.event.addListener(geolocation, 'complete', self.onComplete)
          AMap.event.addListener(geolocation, 'error', self.onError)
        })
  }
     onComplete (data:any) {
      // data是具体的定位信息
      this.form.market_gps = data.formattedAddress
      console.log(data,'成功');
      
    }
  
     onError (data:any) {
      // console.log(data,'失败');
      this.ipLocation()
      this.$toast('定位获取失败，请开启定位服务或您的网络不佳请切换网络')
    }
    
    ipLocation() {
      AMap.plugin('AMap.CitySearch', function () {
        var citySearch = new AMap.CitySearch()
        citySearch.getLocalCity(function (status:any, result:any) {
          if (status === 'complete' && result.info === 'OK') {
            // 查询成功，result即为当前所在城市信息
            console.log(result,'result');
            
          }
        })
      })
    }

  //网格员信息
  public async formGridc() {
    let data = await formGridc()
    this.form.check_name = JSON.parse(JSON.stringify(data.fullname))
    this.form.grid_name = JSON.parse(JSON.stringify(data.grid_name))
    // this.form.
    //街道
    // this.townLabel = value.label;
    this.form.town_id = data.town_id
    // this.townLabel = this.town.
    for( let i = 0; i < this.town.length; i ++) {
       let key = this.town[i].value
       
       if(key == this.form.town_id) {
          this.defaultKey = i
          this.townLabel = this.town[i].label
       }
    }
     this.keyGroup()

  }
  //获取常量
  public async formConst() {
    const data = await formConst();
    const marketCate = data.market_cate;
    const marketProblem = data.market_problem;
    const town = data.town;
    for (const i in marketCate) {
      this.marketCate.push({
        label: marketCate[i],
        value: i
      });
    }
    for (const i in marketProblem) {
      this.marketProblem.push({
        label: marketProblem[i],
        value: i
      });
    }
    for (const i in town) {
      this.town.push({
        label: town[i],
        value: i
      });
    }
    this.formGridc()
  }
  public townConfirm(value: any) {
    this.townLabel = value.label;
    this.form.town_id = value.value
    this.showPicker = false;
  }
  //过滤mn，ma，gn
  getFilter(value:any,key:string) {
    if(key) {
      return value.filter((item:any) => {
         return item.words.indexOf(key) !== -1
      })
    }else {
      return []
    }
  }
  //所属网格
  async inputGridName(key:string) {
    this.gn = JSON.parse(localStorage.getItem('gn') as any) || []
    this.gridName = this.getFilter(this.gn,key) || []

     

    let isHave = this.gn.some((item:any) => {
       return item.words === key
    })
    console.log(isHave,'ishave');
    
    if(key && !isHave) {
    this.$set(this.gnArr,0, {type: 'gn', words: key})
    }
  }
  async keyAdd() {
    // if(this.gnArr.length === 0) {
    //    this.gnArr = [{type:'gn',words:this.form.grid_name}]
    // }
    // let setGn = this.gn.concat(this.gnArr)

   
    this.gn = JSON.parse(localStorage.getItem('gn') as any) || []

    this.gnArr = this.getFilter(this.gn,this.form.grid_name) || []
    if(this.gnArr.length === 0) {
     this.gnArr = [{type:'gn',words:this.form.grid_name}]
    }

   console.log(this.gnArr,'arr');
   

    let setGn = this.gn.concat(this.gnArr) || []
    console.log(setGn,'gngnn');
    setGn = setGn.reduce((pre:any,cur:any)=>{
        if(!pre.includes(cur)){
          return pre.concat(cur)
        }else{
          return pre
        }
    },[])
    
    let setMn = this.mn.concat(this.mnArr) || []
    let setMa = this.ma.concat(this.maArr) || []
    localStorage.setItem('mn', JSON.stringify(setMn))
    localStorage.setItem('ma', JSON.stringify(setMa))
    localStorage.setItem('gn', JSON.stringify(setGn))
    let mn = JSON.parse(localStorage.getItem('mn') as any) || []
    let ma = JSON.parse(localStorage.getItem('ma') as any) || []
    let gn = JSON.parse(localStorage.getItem('gn') as any) || []

    this.index = +(localStorage.getItem('index') as string) + 1
    localStorage.setItem('index',String(this.index))
    if(this.index % 2 === 0) {
      mn = mn.map((item:any) => {
        return item.words
      })
      ma = ma.map((item:any) => {
        return item.words
      })
      gn = gn.map((item:any) => {
        return item.words
      })
      await keyAdd({data:{mn,ma,gn}})
    }
  }
  //场所名称
  public inputName(key: string) {
    this.mn = JSON.parse(localStorage.getItem('mn') as any) || []
    this.wordsName = this.getFilter(this.mn,key) || [] 
    let isHave = this.mn.some((item:any) => {
       return item.words === key
    })

    if(key && !isHave) {
      this.$set(this.mnArr,0, {type: 'mn', words: key})
    }
  }
  //选中场所名称
  clickName(value: string) {
    this.form.market_name = value
    this.wordsName = []
  }
  //选择网格
  clickGridName(value: string) {
    this.form.grid_name = value
    this.gridName = []
  }
  //场所地址
  public inputAddress(key: string) {
    this.ma = JSON.parse(localStorage.getItem('ma') as any) || []
    this.wordsAddress = this.getFilter(this.ma,key) || []

    let isHave = this.ma.some((item:any) => {
       return item.words === key
    })
     if(key && !isHave) {
       this.$set(this.maArr,0, {type: 'ma', words: key})
     }

  }
  //选中场所地址
  clickAddress(value: string) {
    this.form.market_address = value
    this.wordsAddress = []
  }
  //监听复选框
  changeBox(value: number[]) {
    let key = Number(this.marketProblem[this.marketProblem.length-1].value)
    if(value.includes(key)) {
      this.showOther = true
    }else {
      this.showOther = false
    }
  }
  //选择时间
  public selectDate(value:any) {
    // console.log(this.formatDateToString(value));
    this.form.check_at = this.formatDateToString(value)
    this.showDate = false;
  }
  public async submit() {
    if(!this.form.town_id) {
      this.$toast('请选择所属乡镇街道')
      return false
    }
    if(!this.form.grid_name) {
      this.$toast('请输入所属网格')
      return false
    }
    if(!this.form.check_name) {
      this.$toast('请输入检查人姓名')
      return false
    }
    if(!this.form.check_at) {
      this.$toast('选选择检查时间')
      return false
    }
    if(!this.form.market_name) {
      this.$toast('请输入场所详细名称')
      return false
    }
    if(!this.form.market_address) {
      this.$toast('请输入场所详细地址')
      return false
    }
    if(!this.form.market_cate) {
      this.$toast('请选择场所类别')
      return false
    }
    if(this.form.market_problem.length === 0) {
      this.$toast('请选择存在问题')
      return false
    }
    if(!this.form.market_status) {
      this.$toast('请选择现场整改')
      return false
    }
    await formAdd(this.form)
    this.keyAdd()
 


    this.$toast('提交成功')
    this.$dialog.alert({
      message: '提交成功'
    }).then(() => {
      window.location.reload()
    });
  }
  logout() {
    toLogin()
  }
  // 时间转化
  formatDateToString(myDate: Date) {
    const year = myDate.getFullYear();
    let month: string | number = myDate.getMonth() + 1;
    let date: string | number = myDate.getDate();

    month = month < 10 ? "0" + month : month;
    date = date < 10 ? "0" + date : date;

    return `${year}-${month}-${date}`;
  }
}
</script>
<style lang="scss">
.page-home {
  background-color: #fff;
  .banner {
    width: 100%;
    img {
      width: 100%;
      display: block;
    }
  }
  .title {
    font-size: 40px;
    text-align: center;
    margin: 20px 0;
  }
  .form {
    padding: 0 30px;
    .van-form .van-cell .van-cell__title {
      text-align: left;
    }
    .desc {
      color: $gray1;
      font-size: 28px;
    }
    .van-radio-group {
      display: inherit !important;
      .van-radio + .van-radio {
        margin-left: 0px !important;
        // margin-top: 20px;
        // display: inline-block;
      }
      .van-radio {
        margin-top: 20px;
      }
    }
    .van-checkbox {
      margin-top: 20px;
    }
  }
  .van-button--primary {
    background-color: #1989fa;
    border: 1px solid #1989fa
  }
  .market-name {
    .van-field {
      padding-bottom: 0;
    }
    .box {
      width: 100%;
      margin-bottom: 30px;
      border: 1px solid $border1;
      box-sizing: border-box;
      padding: 5px 15px;
      font-size: 28px;
    }
  }
  .upload-img {
    display: flex;
    flex-wrap: wrap;
    img {
      width: 156px !important;
      height: 156px !important;
      margin-right: 20px;
      margin-top: 10px;
      display: block;
    }
    .van-uploader {
      margin-top: 10px !important;
    }
  }
  .logout {
    margin-top: 40px;
    margin-right: 10px;
  }
}
</style>
